package org.eoti.math.cf;

import org.eoti.math.Fraction;

import java.math.BigDecimal;
import java.math.BigInteger;

/*
 * The MIT License
 *
 * Copyright (c) 2009 Malachi de AElfweald <malachid@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
public class CFUtil
{
	public static Fraction converge(ContinuedFraction cf, int convergence)
	{
		int count = 0;
		Fraction last = null;
		for(Fraction fraction : cf.getConvergents())
		{
			if(fraction == null) return last;
			if(count > convergence) return fraction;
			count++;
		}
		return last;
	}

	public static BigDecimal compute(ContinuedFraction cf, int numDigits)
	{
		BigDecimal current = null;
		Fraction last = null;
		for(Fraction fraction : cf.getConvergents())
		{
			if(fraction == null)
			{
				break;
			}
			if(last == null)
			{
				last = fraction;
				continue;
			}

			current = fraction.inCommon( last, numDigits + 2);
			if(current != null)
			{
				String s = current.toPlainString();
				int length = s.length();
				boolean hasPeriod = s.indexOf('.') != -1;
				if( (length > numDigits) || (length==numDigits && !hasPeriod))
						return new BigDecimal(s.substring(0, (hasPeriod?numDigits+1:numDigits)));
			}

			last = fraction;
		}

		if(current == null) // ie: CFInteger
		{
			if(last == null) return null;
			
			int scale = 0;
			if(last.getDenominator() != null)
				scale += last.getDenominator().toString().length();
			if(last.getNumerator() != null)
				scale += last.getNumerator().toString().length();

			return last.compute(scale);
		}

		String s = current.toPlainString();
		int length = s.length();
		boolean hasPeriod = s.indexOf('.') != -1;
		if((hasPeriod && length < (numDigits+1)) || (length < numDigits))
		{
			current = last.compute( numDigits + 2 );
			length = s.length();
			hasPeriod = s.indexOf('.') != -1;
			if(hasPeriod && length > (numDigits+1)) return new BigDecimal(current.toPlainString().substring(0, numDigits+1));
			if(length > numDigits) return new BigDecimal(current.toPlainString().substring(0, numDigits));
			return current;
		}

		return current;
	}

	public static String toString(ContinuedFraction cf, int numDigits)
	{
		BigDecimal val = compute(cf, numDigits);
		if(val == null) return null;
		return val.stripTrailingZeros().toPlainString();
	}

	public static String normalize(ContinuedFraction cf, int numTerms)
	{

		// step one, let's see if it is a simple/regular cf or a generalized cf
		int terms = 0;
		boolean isSimple = true;
		for(Fraction fraction : cf.getValues())
		{
			if(!BigInteger.ONE.equals(fraction.getNumerator()))
			{
				isSimple = false;
				break;
			}
			if(terms > numTerms) break;
			terms++;
		}

		StringBuilder sb = null;
		terms = 1;
		for(Fraction fraction : cf.getValues())
		{
			if(sb == null)
			{
				sb = new StringBuilder();
				sb.append("[");
				if(fraction.getDenominator() == null) break;
				sb.append(fraction.getDenominator());
				if(fraction.getNumerator() == null) break;
				sb.append(";");
				if(!isSimple) sb.append(fraction.getNumerator());
			}else{
				if(fraction.getDenominator() == null) break;
				if(!isSimple) sb.append("/");
				sb.append(fraction.getDenominator());
				if(fraction.getNumerator() == null) break;
				sb.append(",");
				if(!isSimple) sb.append(fraction.getNumerator());
			}

			if(terms >= numTerms)
			{
				sb.append(" ...");
				break;
			}

			terms++;
		}

		if(sb == null) return null;
		
		String s = sb.toString();
		while(s.endsWith(" ") || s.endsWith(",") || s.endsWith(";"))
		{
			sb.deleteCharAt( sb.length()-1 );
			s = sb.toString();
		}

		sb.append("]");
		return sb.toString();
	}
}
